/*
 * Author: JacksonCoder
 * FileName: ConcurrentMethodCall
 * Version: 1.0.0
 * Date: 2025/2/17
 */

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class ConcurrentMethodCall {

    public static void main(String[] args) {
        // 调用并发执行方法
        CompletableFuture<String> result = executeConcurrently();

        // 等待结果
        try {
            String outcome = result.get();
            System.out.println("最终结果: " + outcome);
        } catch (InterruptedException | ExecutionException e) {
            System.out.println("所有方法都失败了");
        }
    }

    // 并发执行方法
    public static CompletableFuture<String> executeConcurrently() {
        // 创建三个异步任务
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> method1());
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> method2());
        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> method3());

        // 使用anyOf组合三个任务，只要有一个成功就返回成功结果
        CompletableFuture<Object> anyOfFuture = CompletableFuture.anyOf(future1, future2, future3);

        // 将返回值转换为String类型
        return anyOfFuture.thenApply(result -> {
            if (result instanceof String) {
                return (String) result;
            }
            return null;
        });
    }

    // 示例方法1
    private static String method1() {
        try {
            System.out.println("方法1正在执行...");
            TimeUnit.SECONDS.sleep(2); // 模拟耗时操作
            return "方法1成功";
        } catch (InterruptedException e) {
            throw new RuntimeException("方法1失败");
        }
    }

    // 示例方法2
    private static String method2() {
        try {
            System.out.println("方法2正在执行...");
            TimeUnit.SECONDS.sleep(1); // 模拟耗时操作
            return "方法2成功";
        } catch (InterruptedException e) {
            throw new RuntimeException("方法2失败");
        }
    }

    // 示例方法3
    private static String method3() {
        try {
            System.out.println("方法3正在执行...");
            TimeUnit.SECONDS.sleep(3); // 模拟耗时操作
            return "方法3成功";
        } catch (InterruptedException e) {
            throw new RuntimeException("方法3失败");
        }
    }

}
